package com.allwees.data.analysis.base.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.allwees.bs.core.modelbase.vo.R;
import com.allwees.core.elasticsearch.query.QueryParams;
import com.allwees.core.elasticsearch.query.sql.EsSqlQuery;
import com.allwees.data.dataport.common.api.BaseApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 *
 *
 * @author yangylsky
 * @since 2020-04-08
 *
 */
@Slf4j
@RestController
@RequestMapping("/data/api/analysis/common")
public class BaseAnalysisApi extends BaseApi {
	@Autowired
	protected EsSqlQuery esSqlQuery;

	protected Object query(String fileUri, Date dateFrom, Date dateTo) {
    	QueryParams params = QueryParams.of()
    			.put("dateFrom", dateFrom)
    			.put("dateTo", dateTo);
        JSONObject jsonObject = esSqlQuery.queryJsonObj(fileUri, params);
        //log.info("=============jsonObject：========{}",jsonObject);
        return parseEsResult(jsonObject);
    }

    protected Object parseEsResult(JSONObject jsonObject) {
	    JSONArray element =  (JSONArray)jsonObject.get("rows");
        if(element.size() > 0){
            JSONArray array = (JSONArray)element.get(0);
            if (array.size() > 0) {
                return array.get(0);
            }
        }
        return null;
    }

    @GetMapping("/sys/clear_query_cache")
    public R clearQueryCache() {
    	esSqlQuery.clearQueryCache();
        return R.ok("clear query cache successfully");
    }

    @GetMapping("/{fileUri}")
    public R commonQuery(@PathVariable("fileUri") String fileUri, Date dateFrom, Date dateTo) {
        return R.ok(query(fileUri.replaceAll("-", "/") + ".txt", dateFrom, dateTo));
    }
}
